<template>
  <div class='container'>
    <el-form class="filter-container" label-position="left" label-width="68px">
      <el-row :gutter="24">
        <el-col :span="4">
          <el-form-item label="名称" style="margin-bottom: 0!important;">
            <el-input @keyup.enter.native="getList" class="filter-item" placeholder="请输入名称" v-model="listQuery.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="创建时间" style="margin-bottom: 0!important;">
            <el-date-picker type="datetimerange" :default-time="['00:00:00', '23:59:59']"
              @keyup.enter.native="getList" class="filter-item" align="right"
              range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" v-model="time" :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-button class="filter-item" type="primary" icon="el-icon-search" @click="getList">{{$t('table.search')}}</el-button>
        <el-button class="filter-item" @click="handleCreate" type="success" icon="el-icon-plus">新增</el-button>
        <el-button class="filter-item" @click="handleDelete" type="danger" icon="el-icon-delete">删除</el-button>
        <a :href="downloadInfo.url" :download="downloadInfo.name">
          <el-button class="filter-item" type="warning" icon="el-icon-download">下载Excel模板</el-button>
        </a>
        <el-button class="filter-item" :loading="true" v-if="!!uploadFileInfo.loading" type="warning">上传中</el-button>
        <el-upload
          ref="uploadButton"
          :action="wordFileUploadUrl"
          :headers="{Authorization: 'Bearer ' + $store.getters.token}"
          style="display: inline;"
          :on-success="startParse"
          :before-upload="beforeUpload"
        >
        <el-button class="filter-item" v-if="!uploadFileInfo.loading" type="success" icon="el-icon-upload">上传Excel</el-button>
      </el-upload>
      </el-row>
    </el-form>


    <el-table stripe
      :data="tableData" v-loading="listLoading" element-loading-text="加载中..." border fit
      highlight-current-row @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column align="center" type="selection" width="55">
      </el-table-column>
      <!--<el-table-column align="center" type="index" label="序号" width="55">-->
      <!--</el-table-column>-->
      <el-table-column align="center" label="名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime}}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center" label="操作" width="90" class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-tooltip content="编辑" placement="top">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
              class="button-icon el-icon-edit"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="listQuery.pageNum"
        :page-sizes="[10,20,30, 50]" :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper" :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="130px"
        style='margin: 24px;'
      >
        <el-form-item label="名称" prop="name">
          <el-select v-model="temp.name" :clearable="true"
            remote reserve-keyword :remote-method="filterWord"
            filterable placeholder="请选择">
            <el-option
              v-for="(item,index) in filterwordList"
              :key="index"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { wordListSimple, wordFileUploadUrl } from '../../api/word'
  import {
    imageWordList,
    imageWordAdd,
    imageWordDelete,
    imageWordUpdate,
    imageFileDelete,
    imageFileParse,
    imageUploadUrl
  } from '../../api/imageManagement'
  import { baseUrl } from '@/utils/request'
  import pinyin from 'pinyin'

  export default {
    name: 'List',
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val)
      }
    },
    created() {
      this.getList()
      this.getWordListSimple()
    },
    methods: {
      handleSelectionChange(val) {
        this.multipleSelection = val.map(e => e.id)
      },
      getList() {
        this.listLoading = false
        if (this.time) {
          this.listQuery.startTime = this.time[0]
          this.listQuery.endTime = this.time[1]
        } else {
          this.listQuery.startTime = ''
          this.listQuery.endTime = ''
        }
        imageWordList(this.listQuery).then(response => {
          this.tableData = response.Data
          this.total = response.PageInfo.Total * 1
          this.listLoading = false
        })
      },
      getWordListSimple() {
        const params = {
          type: 1,
          pageNum: 1,
          pageSize: 999999
        }
        wordListSimple(params).then(response => {
          this.allWordList = response.Data
        })
      },
      filterWord(query) {
        if (query !== '') {
          let result = this.allWordList.filter(item => {
            return item.indexOf(query) > -1 || pinyin(item, {
              style: pinyin.STYLE_FIRST_LETTER,
              heteronym: true
            }).join('').indexOf(query) > -1
          }).sort((a, b) => a.length - b.length)
          if (result.length >= 100) {
            this.$message({
              message: '菜单超过100条，只显示前100条，请输入更多信息'
            })
            result = result.slice(0, 99)
          }
          this.filterwordList = result
        } else {
          this.filterwordList = []
        }
      },
      handleSizeChange(val) {
        this.listQuery.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: '',
          name: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const params = {
              name: this.temp.name
            }
            imageWordAdd(params).then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            imageWordUpdate(tempData).then(() => {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete() {
        if (this.multipleSelection.length === 0) return
        this.$confirm('确认删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          imageWordDelete({ batchIds: this.multipleSelection }).then(() => {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      beforeUpload(file) {
        console.log(file.type)
        const isJPG = (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (file.type === 'application/vnd.ms-excel')
        const isLt2M = file.size / 1024 / 1024 < 1
        this.uploadFileInfo.loading = true
        this.uploadFileInfo.status = '上传中...'
        if (!isJPG) {
          this.$message.error('请上传Excel文件！')
          this.uploadFileInfo.loading = false
        }
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 1MB!')
          this.uploadFileInfo.loading = false
        }
        return isJPG && isLt2M
      },
      startParse(response, file, fileList) {
        this.uploadFileInfo.status = '解析中...'
        const params = {
          operateType: 2,
          fileName: response.Data[0].fileName
        }
        imageFileParse(params).then((response) => {
          this.getList()
          this.$alert('本次导入影响数据' + response.Data[0].successNum + '条', '提示', {
            confirmButtonText: '确定',
            type: 'success'
          })
          const clearFile = () => {
            fileList.splice(fileList.indexOf(file), 1)
          }
          setTimeout(clearFile, 5000)
          this.uploadFileInfo.loading = false
        }).catch(() => {
          this.uploadFileInfo.loading = false
          this.$refs.uploadButton.clearFiles()
        })
      }
    },
    data() {
      return {
        wordFileUploadUrl: wordFileUploadUrl,
        uploadFileInfo: {
          loading: false,
          status: ''
        },
        filterwordList: [],
        allWordList: [],
        total: null,
        listLoading: false,
        showButton: false,
        tableName: '词汇标签管理',
        time: ['', ''],
        listQuery: {
          pageNum: 1,
          pageSize: 20,
          search: undefined
        },
        filterText: '',
        props: {
          label: 'name',
          id: 'id'
        },
        textMap: {
          update: '编辑',
          create: '新增'
        },
        dialogStatus: '',
        dialogFormVisible: false,
        tableData: [],
        temp: {
          id: '',
          name: ''
        },
        rules: {
          id: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }],
          name: [{ type: 'string', required: true, message: '请输入...', trigger: 'change' }]
        },
        downloadInfo: {
          url: baseUrl + 'template/图库词汇上传模板.xlsx',
          name: '图库词汇上传模板'
        },
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近三天',
            onClick(picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24 * 3
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const end = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1).getTime() - 1000
              const start = end + 1000 - 3600 * 1000 * 24 * 7
              picker.$emit('pick', [start, end])
            }
          }]
        }
      }
    }
  }
</script>

<style type="scss" scoped>
  .col {
    margin: auto;
  }

  .card-body {
    margin-top: 1rem;
  }

  .form {
    max-width: 500px !important;
    margin: auto !important;
  }
</style>

<style>
  .el-tag {
    margin-right: 3px;
    background-color: rgba(64, 158, 255, .1);
    color: #409EFF;
    border-radius: 4px;
    padding: 0 3px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    border: 1px solid rgba(64, 158, 255, .2);
  }
</style>
